package com.mall.service;

import com.mall.mapper.loginMapper;
import com.mall.pojo.Result;
import com.mall.pojo.login;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class loginService {
    //加密密钥
    private static final String SECRET_KEY = "SECRET_KEY_SET_IN_2025_4_20_BY_WHU";
    //主题
    private static final String SUBJECT = "EMall";
    @Autowired
    private loginMapper loginMapper;
    public Result getLoginByAccount(String account,String password) {
       login login= loginMapper.getLoginByAccount(account);
       if(login==null){throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "账号不存在");}
       if(!login.getPassword().equals(password)){
           throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "密码错误");
       }
       login.setPassword(null);

       Map<String,Object> claims = new HashMap<>();
       claims.put("account",account);
       claims.put("password",password);
       String token = Jwts.builder().claims()
                    .add(claims)  // 添加内容
                    .subject(SUBJECT)   // 声明主题
                    .issuedAt(new Date())   // 创建JWT时的时间戳
                    .expiration(new Date(System.currentTimeMillis() + 600000*24))  // 设置过期时间 
                    .and()  // 返回JwtBuilder配置
                    .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))  // 签名
                    .compact(); // 紧凑
        login.setToken(token);
        return Result.success(login);
    }
}
